package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.ISkuStockService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.product.vo.SkuLockVo;
import com.spzx.product.vo.SkuStockVo;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品sku库存表 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2025-04-28
 */
@Service
@RequiredArgsConstructor
public class SkuStockServiceImpl extends ServiceImpl<SkuStockMapper, SkuStock> implements ISkuStockService {
    private final RedisTemplate redisTemplate;
    @Override
    public SkuStockVo getSkuStock(Long skuId) {
        LambdaQueryWrapper<SkuStock> select = new LambdaQueryWrapper<SkuStock>()
                .eq(SkuStock::getSkuId, skuId)
                .select(SkuStock::getAvailableNum, SkuStock::getSaleNum);
        SkuStock skuStock = baseMapper.selectOne(select);
        SkuStockVo skuStockVo = new SkuStockVo();
        skuStockVo.setSkuId(skuId);
        skuStockVo.setAvailableNum(skuStock.getAvailableNum());
        skuStockVo.setSaleNum(skuStock.getSaleNum());
        return skuStockVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String checkAndLock(String orderNo, List<SkuLockVo> skuLockVoList) {
        //1.遍历商品扣减VO列表，检查是否满足锁定库存条件，为VO中的属性是否有库存赋值
        //遍历过程中如果满足锁定库存，采用MySQL悲观锁锁定：select + for update，并根据结果判断是否有库存，有库存把vo设置为true反之亦然
        for (SkuLockVo skuLockVo : skuLockVoList) {
            SkuStock check = baseMapper.check(skuLockVo.getSkuId(), skuLockVo.getSkuNum());
            if(check!=null){
                skuLockVo.setHaveStock(true);
            }else{
                // flag = true;
                skuLockVo.setHaveStock(false);
            }
        }
        boolean flag = skuLockVoList.stream().anyMatch(skuLockVo -> !skuLockVo.isHaveStock());
        StringBuilder stockErrorMsg = new StringBuilder();
        //2.读取列表如果任意一件商品无法锁定库存，表示锁定失败，封装锁定库存商品提示信息：stockErrorMsg
        //首先遍历列表，找出没有锁定成功的商品
        if(flag){
            for (SkuLockVo skuLockVo : skuLockVoList) {
                if(!skuLockVo.isHaveStock()){
                    SkuStock skuStock = baseMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, skuLockVo.getSkuId()));
                    stockErrorMsg.append(skuLockVo.getSkuName())
                            .append("库存不足，当前剩余：")
                            .append(skuStock.getAvailableNum())
                            .append(";");
                }
            }
            return stockErrorMsg.toString();
        }
        //3.如果锁定成功，则调用数据库锁定方法,并将锁定后的库存信息存储在Redis中用于取消订单解锁库存/支付成功解锁库存并扣减
        for (SkuLockVo skuLockVo : skuLockVoList) {
            baseMapper.lock(skuLockVo.getSkuId(),skuLockVo.getSkuNum());
        }
        String dataKey = "sku:lock:data:" + orderNo;
        redisTemplate.opsForValue().set(dataKey,skuLockVoList);
        return null;
    }

    @Override
    public void unlock(String orderNo) {
        //幂等性处理，就是setnx
        String key = "sku:unlock"+orderNo;
        Boolean notExist = redisTemplate.opsForValue().setIfAbsent(key, orderNo, 1, TimeUnit.HOURS);
        if(!notExist){
            return ;
        }
        //获取被锁定库存的缓存信息，能从对应的键拿到 skuLockVoList
        String dataKey = "sku:lock:data:" + orderNo;
        List<SkuLockVo> skuLockVoList =(List<SkuLockVo>) redisTemplate.opsForValue().get(dataKey);
        if(CollectionUtils.isEmpty(skuLockVoList)){
            return;
        }
        //解锁库存
        skuLockVoList.forEach(skuLockVo -> baseMapper.unlock(skuLockVo.getSkuId(),skuLockVo.getSkuNum()));
        //删除之前的锁定缓存
        redisTemplate.delete(dataKey);
    }
}
